from datetime import datetime
from django.core.management.base import BaseCommand 
from ability.models import  Image, Instance, VncServer
from tencentcloud.cvm.v20170312 import models
import re
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from ability.cloud import CloudInstance 
from study.utils import kill_process_by_port


class Command(BaseCommand):
    help = 'recovery all the experied instance'

    def handle(self, *args, **options):
      instances = Instance.objects.filter(experied_ts__lt=datetime.now(), status='N').all()
      insIds = []
      if len(instances) == 0:
        print('no instance need to be recovery')
        return
      for ins in instances:
        insIds.append(ins.instanceId)
        # recovery the vnc port
        vncServers = VncServer.objects.filter(host=ins.ip_address).values('host', 'port')
        for item in vncServers:
          kill_process_by_port(item['port'])
        VncServer.objects.filter(host=ins.ip_address).delete()

      ci = CloudInstance()
      # print('recovery instance: ', insIds)
      try:
        print('回收已到截止时间但并未关机的实例: ', insIds)
        ci.recovery(insIds)
        for ins in instances:
          ins.status = 'C'
          print(ins)
          ins.save()
      except TencentCloudSDKException as e:
        print(e.code)
        if e.code == 'InvalidInstanceId.NotFound':
          # 如果需要将字符串转换为列表
          instances_str = e.message
          # print(instances_str[instances_str.find('[')+1:instances_str.find(']')])
          # print(instances_str[instances_str.find('[')+1:instances_str.find(']')].split(","))
          instance_ids_list = [id.strip().strip("'") for id in instances_str[instances_str.find('[')+1:instances_str.find(']')].split(",")]
          print("实例ID列表:", instance_ids_list)
          Instance.objects.filter(instanceId__in=instance_ids_list).update(status='C')
        print(f"An error occurred: {e}")
      except Exception as e:
        print(e)